package com.lyh.common.utils.http;


import com.lyh.common.utils.http.model.SSLClient;
import lombok.extern.java.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

/**
 * http工具类
 */
@Log
public class HttpClientUtil {

    public static String doPost(String url,String json,String charset) throws Exception{
        HttpClient httpClient = null;
        HttpPost HttpPost = null;
        String result = null;
        httpClient = new SSLClient();
        HttpPost = new HttpPost(url);
        HttpPost.addHeader("Content-Type", "application/json");
        StringEntity se = new StringEntity(json);
        se.setContentType("text/json");
        se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
        HttpPost.setEntity(se);
        HttpPost.setConfig(RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(5000).build());
        HttpResponse response = httpClient.execute(HttpPost);
        if(response != null){
            HttpEntity resEntity = response.getEntity();
            if(resEntity != null){
                result = EntityUtils.toString(resEntity,charset);
            }
        }
        return result;
    }

    public static String doGet(String url,String charset) throws Exception{
        HttpClient httpClient = null;
        HttpGet Httpget = null;
        String result = null;
        httpClient = new SSLClient();
        Httpget = new HttpGet(url);
        Httpget.addHeader("Content-Type", "application/json");
        HttpResponse response = httpClient.execute(Httpget);
        if(response != null){
            HttpEntity resEntity = response.getEntity();
            if(resEntity != null){
                result = EntityUtils.toString(resEntity,charset);
            }
        }
        return result;
    }
}
